package com.zm.cc.web;

import com.zm.cc.Result;
import com.zm.cc.Utils;
import com.zm.cc.entity.Fav;
import com.zm.cc.entity.User;
import com.zm.cc.service.BizException;
import com.zm.cc.service.IFavService;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addFav")
public class AddFavServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        user.setId(1);

        String name = req.getParameter("name");
        String addr = req.getParameter("addr");
        String tags = req.getParameter("tags");
        String intro = req.getParameter("intro");
        String image = req.getParameter("image");
        Integer id = null;
        if(req.getParameter("id")!=null){
            id = Integer.valueOf(req.getParameter("id"));
        }
        Fav fav = new Fav();
        fav.setAddr(addr);
        fav.setName(name);
        fav.setTags(tags);
        fav.setIntro(intro);
        fav.setImage(image);
        fav.setUid(1);
        fav.setId(id);
        Result result = new Result();

        ApplicationContext cxt = (ApplicationContext) this.getServletContext().getAttribute("cxt");
        IFavService dao = cxt.getBean(IFavService.class);

        try {
            if(fav.getId() == null){
                dao.add(fav);
                result.setCode(1);
                result.setMsg("添加成功");
            }else{
                dao.modyfi(fav);
                result.setCode(2);
                result.setMsg("修改成功");
            }


        } catch (BizException e) {
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }catch (RuntimeException e){
            result.setCode(-2);
            result.setMsg("系统繁忙，添加失败");
        }
        Utils.print(resp,result);
    }
}
